<template>
	<image :src="imageSrc" @error="imageError" :id="classId" :class="className" :style="classStyle" :mode="mode"
		:show-menu-by-longpress="showMenu" />
</template>

<script>
	export default {
		name: 'fileImage',
		data() {
			return {
				imageSrc: '', // 图片真实url地址
				windowHeight: 667, // 可使用窗口高度
				loading: false, // 判断当前url是否请求
			}
		},
		props: {
			// 照片图片消息
			src: {
				type: String,
				default: ''
			},
			// 图片切割方式
			mode: {
				type: String,
				default: 'aspectFill'
			},
			// 开启长按图片显示识别小程序码菜单
			showMenu: {
				type: Boolean,
				default: false
			},
			// 样式name，小程序样式会不生效
			className: {
				type: Array,
				default: () => {
					return []
				}
			},
			// 自定义样式 width:30rpx;height:30rpx
			classStyle: {
				type: String,
				default: ''
			},
			// 自定义默认图片、
			defaultImg: {
				type: String,
				default: ''
			},
			// 当前组件id
			classId: {
				type: String,
				default: ''
			},
			scrollTop: {
				type: Number,
				default: 0
			},
			// 偏移量
			offset: {
				type: Number,
				default: 20
			}
		},
		created() {
			if (!this.classId) return
			var _that = this
			uni.getSystemInfo({
				success: function(res) {
					_that.windowHeight = res.windowHeight
				}
			});
		},
		mounted() {
			if (this.classId) {
				this.imgSrcTopSrcoll()
			} else {
				this.imageSrc = this.src ? this.src : this.daleultFunc()
			}
		},
		watch: {
			src(val) {
				this.imageSrc = val ? val : this.daleultFunc()
			},
			scrollTop(newValue, oldValue) {
				console.log(newValue, oldValue)
				if (newValue - oldValue > this.offset) {
					this.imgSrcTopSrcoll()
				}
			}
		},
		methods: {
			imageError(e) {
				// 图片
				this.imageSrc = this.daleultFunc()
				this.$emit('errorImage', this.src)
			},
			daleultFunc() {
				if (this.defaultImg) return this.defaultImg
				else return '/static/imagedefault.png'
			},
			imgSrcTopSrcoll() {
				if (this.loading) {
					console.log('缓存===============================')
					return
				}
				const query = uni.createSelectorQuery().in(this);
				query.select(`#${this.classId}`).boundingClientRect(data => {
					// console.log("得到布局位置信息",data)
					// console.log("节点离页面顶部的距离为" + data.top);
				 if (data.top - this.scrollTop < this.windowHeight) {
						console.log(data, '-------------------------')
						this.imageSrc = this.src ? this.src : this.daleultFunc()
						this.loading = true
					} else {
						this.imageSrc = this.daleultFunc()
						this.loading = false
					}
				}).exec();
			}
		},
	}
</script>
